#include "FileManager.h"

void FileManager::log(const char* arg) const{
	std::ofstream file;

	file.open("log.txt", std::ios::trunc);

	file << arg << "\n";

	file.close();
}

//v1.0: A lot of error checking, but still returns undefined if something fails...
//v2.0: Fixed it!  I'm an idiot.  Pass by reference still works.  Push to git NOW!
bool FileManager::readFile(const char* path, int width, int height, std::vector<std::unique_ptr <TileEntity> > &tiles) const{
	int x = 0;
	int y = 0;

	std::ifstream file;

	try{
		file.open(path);
	}catch (...){
		log("Failure Opening Map");

		return false;
	}

	if(file == NULL){
		log("ID10T Error: File Not Found");

		return false;
	}

	int num, type, collision;
	
	if(file != NULL){
		while(!file.eof()){
			file >> num >> type >> collision;

			if(file.fail()){
				log("Map Randomly Failed.  Recovering...");
				log("Rewriting Alpha protocol...");
				log("Simulating binary data...");
				log("Using Globotron 3000 (TM)...");
				log("Success! No data recovered.");

				file.close();
			}

			std::unique_ptr<TileEntity> temp(new TileEntity(num, type, collision));

			tiles.push_back(std::move(temp));

			//tiles[i]->collisionRect = collision; ADD RECTANGLE

			x += 32;

			if(x >= width){
				x = 0;
			
				y += 32;
			}
		}

		file.close();
	}

	return true;
}

FileManager::~FileManager(){
	
}